import React, { useEffect, useState } from 'react'
import { IAntSelectOption, IEmployee, IProject, IProjectManager } from '../../../starter/model/interfaces'
import style from './cardProject.module.scss'
import { Button, ButtonProps, Progress, Select } from 'antd'
import dayjs from 'dayjs'
import { DATE_FORMAT } from '../../../starter/constants'
import { PlusIcon } from '../../../images/icons'
import { useAppSelector } from '../../../starter/hooks/redux'
import { CheckOutlined, CloseOutlined, EditOutlined } from '@ant-design/icons'
import { useUpdateEmployeeMutation } from '../../../starter/api/employeesApi'
import { useLazyGetProjectsQuery, useUpdateProjectMutation } from '../../../starter/api/projectsApi'
import PersonInfo from '../PersonInfo/PersonInfo'
import { useUpdateProjectManagerMutation } from '../../../starter/api/projectManagersApi'
import { store } from '../../../starter/redux/store'
import CreateProject from '../CreateProject/CreateProject'
import { useActions } from '../../../starter/hooks/actions'
import { useDrag } from 'react-dnd'

type TCardProject = {
  project: IProject
  isSmall: boolean
}
export default function CardProject ({project, isSmall}: TCardProject) {
  const [barPercent, setBarPercent] = useState<number>(0)

  const { projectManagers} =useAppSelector(state => state.projectManagers)
  const [showProjectManagers, setShowProjectManagerSelect] = useState<boolean>(false)
  const [projectManagersOptions, setProjectManagersOptions] = useState<IAntSelectOption[]>()
  const [selectedProjectManager, setSelectedProjectManager] = useState<IEmployee | undefined>(project.manager)

  const {employees} =useAppSelector(state => state.employees)
  const [showEmployeeSelect, setShowEmployeeSelect] = useState<boolean>(false)
  const [employeesOptions, setEmployeesOptions] = useState<IAntSelectOption[]>()
  const [selectedResponsibleEmployee, setSelectedResponsibleEmployee] = useState<IEmployee | undefined>(project.responsibleEmployee)

  const [updateProject, {isLoading: isLoadingUpdateProject, isSuccess: isSuccessUpdateProject, isError: isErrorUpdateProject}] = useUpdateProjectMutation()
  const [updateEmployee, {isLoading: isLoadingUpdateEmployee, isSuccess: isSuccessUpdateEmployee, isError: isErrorUpdateEmployee}] = useUpdateEmployeeMutation()
  const [updateProjectManager, {isLoading: isLoadingUpdateProjectManager, isSuccess: isSuccessUpdateProjectManager, isError: isErrorUpdateProjectManager}] = useUpdateProjectManagerMutation()

  const [getLazyProjects, {}] = useLazyGetProjectsQuery()

  const {onShowModal, setModalData, setTmpProject} = useActions()

  useEffect(() => {
    setShowProjectManagerSelect(false)
    setShowEmployeeSelect(false)
    onShowModal(false)
  }, [isSuccessUpdateProject])

  useEffect(() => {
    setProjectManagersOptions(projectManagers.map(p => ({
      value: p._id,
      label: `${p.firstName} ${p.lastName}`
    })))
  }, [projectManagers])

  useEffect(() => {
    getLazyProjects()
  }, [isSuccessUpdateEmployee,isSuccessUpdateProjectManager])

  useEffect(() => {
    setEmployeesOptions(employees.map(p => ({
      value: p._id,
      label: `${p.firstName} ${p.lastName}`
    })))
  }, [employees])

  useEffect(() => {
    if (project) {
      const allPeriodLength = dayjs(project.from).diff(dayjs(project.to), 'days')
      const currentPeriodLength = dayjs().diff(dayjs(project.from), 'days')
      const percent = Math.round(100 * currentPeriodLength / allPeriodLength)
      setBarPercent(percent)
    }
  }, [project])

  const [monitor,projectRef] = useDrag({
    type: 'project',
    item: project,
    collect: monitor => monitor
  })

  const calcBarColor = (percent: Number) => {
    if (percent > 0 && percent < 75) return 'green'
    if (percent >= 75 && percent <= 100) return '#ead503'
    if (percent >100) return 'red'
  }

  const addManagerHandler = () => {
    const _project = {
      ...project,
      manager: selectedProjectManager
    }
    updateProject(_project)
  }
  const addResponsibleEmployee = () => {
    const _project = {
      ...project,
      responsibleEmployee: selectedResponsibleEmployee
    }
    updateProject(_project)
  }

  const editProject = () => {
    onShowModal(true)
    setTmpProject({...project})
    const buttonSet : ButtonProps[] = [
      {
        type: 'primary',
        onClick: () => {
          const {project} = {...store.getState().tmp}
          if (project) {
            updateProject(project)
          }
        },
        children: 'Ok'
      },
      {
        onClick: () => onShowModal(false),
        children: 'Cancel'
      }
    ]
    setModalData({
      title: 'Введите данные проекта',
      content: <CreateProject/>,
      buttonSet,
      footer: buttonSet.map((item, index) => <Button key={index} {...item}/>)
    })
  }

  return (
    <div
      ref={projectRef}
    >
      <div className={style.wrapper}>
        <div className={style.title}>
          <div>
            {project.title}
          </div>
          <EditOutlined style={{cursor: 'pointer'}} onClick={() => {editProject()}}/>
        </div>
        <div className={style.code}>{project.code}</div>
        <div className={style.responsible}>
          <div className={style.card}>
            {
              project.manager &&
              <PersonInfo person={project.manager} onUpdate={updateProjectManager}/>
            }
            {
              !project.manager &&
              <div
                className={style.plusButton}
                onClick={() => {setShowProjectManagerSelect(!showProjectManagers); setShowEmployeeSelect(false)}}
              >
                <PlusIcon/>
                <span className={style.plusButtonTitle}>Менеджера</span>
                { showProjectManagers &&
                  <div className={style.employeeSelect}>
                    <Select
                      showSearch
                      style={{ width: 200 }}
                      value={selectedProjectManager?._id}
                      placeholder="Выберите менеджера"
                      optionFilterProp="label"
                      filterSort={(optionA, optionB) =>
                        (optionA?.label ?? '').toLowerCase().localeCompare((optionB?.label ?? '').toLowerCase())
                      }
                      options={projectManagersOptions}
                      onClick={(e) => e.stopPropagation()}
                      onSelect={(value: string, option: IAntSelectOption) => {setSelectedProjectManager(projectManagers.find(f => f._id === value))}}
                    />
                    <CheckOutlined spin={isLoadingUpdateProject} className={style.approve}
                                   onClick={(e) => {addManagerHandler()}}
                    />
                    <CloseOutlined className={style.cancel}
                                   onClick={(e) => {setSelectedProjectManager(undefined)}}
                    />
                  </div>
                }
              </div>
            }
          </div>
          <div className={style.card}>
            {

                project.responsibleEmployee &&
                  <PersonInfo person={project.responsibleEmployee} onUpdate={updateEmployee}/>

            }
            {
              !project.responsibleEmployee &&
              <div
                className={style.plusButton}
                onClick={() => {setShowEmployeeSelect(!showEmployeeSelect); setShowProjectManagerSelect(false)}}
              >
                <PlusIcon/>
                <span className={style.plusButtonTitle}>Сотрудника</span>
                { showEmployeeSelect &&
                  <div className={style.employeeSelect}>
                    <Select
                      showSearch
                      style={{ width: 200 }}
                      value={selectedResponsibleEmployee?._id}
                      placeholder="Выберите отвественного сотрудника"
                      optionFilterProp="label"
                      filterSort={(optionA, optionB) =>
                        (optionA?.label ?? '').toLowerCase().localeCompare((optionB?.label ?? '').toLowerCase())
                      }
                      options={employeesOptions}
                      onClick={(e) => e.stopPropagation()}
                      onSelect={(value: string, option: IAntSelectOption) => {setSelectedResponsibleEmployee(employees.find(f => f._id === value))}}
                    />
                    <CheckOutlined spin={isLoadingUpdateProject} className={style.approve}
                                   onClick={(e) => {addResponsibleEmployee()}}
                    />
                    <CloseOutlined className={style.cancel}
                                   onClick={(e) => {setSelectedResponsibleEmployee(undefined)}}
                    />
                  </div>
                }
              </div>
            }
          </div>
        </div>
        <div className={style.endTime}>
          {/*поставить посчитанный актуальный период*/}
          {dayjs(project && project.to).format(DATE_FORMAT)}
        </div>
        <div className={style.progressBar}>
          <Progress
            percent={barPercent}
            showInfo={barPercent < 100 && true}
            strokeColor={calcBarColor(barPercent)}
          />
        </div>
      </div>
    </div>
  )
}
